package com.power.sifa.util;

import com.alibaba.fastjson.JSONObject;
import com.plf.common.exception.BusinessException;
import com.plf.common.utils.RestUtil;
import com.plf.common.utils.TrustAllHttpsInitializer;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Map;

/**
 * 腾讯地图地址解析工具
 */
@Data
@Component
@Slf4j
public class GeocoderUtil {


    private static String key;

    private static String url;

    @Value("${tencent.map.key:#{null}}")
    public void setKey(String key) {
        GeocoderUtil.key = key;
    }

    @Value("${tencent.map.geocoder.url:#{null}}")
    public void setUrl(String url) {
        GeocoderUtil.url = url;
    }

    /**
     * 逆地址解析
     * @param location lat,lng 纬度,经度
     * @see <a href="https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder">详细参数</a>
     * @return 地址
     */
    @SneakyThrows
    public static String reverseParseAddress(String location) {

        if (location == null) {
            throw new BusinessException("location参数不能为空");
        }
        RestUtil.HttpClient client = RestUtil.getClient(GeocoderUtil.url).get()
                .addInitializer(new TrustAllHttpsInitializer());
        client.addQueryParam("location", location);
        client.addQueryParam("key", GeocoderUtil.key);
        RestUtil.HttpResponse resp = client.request();
        JSONObject back = (JSONObject) resp.getContent();
        Integer status = (Integer) back.get("status");
        if (status != 0) {
            log.error((String) back.get("message"));
            return null;
        }

        Map result = back.getObject("result", Map.class);
        return (String) result.get("address");
    }
}
